import { app, ipcMain, type BrowserWindow } from "electron";
import { store } from "./store";

export function initSystemIpc(mainWindow: BrowserWindow) {
  // 单例模式
  const gotTheLock = app.requestSingleInstanceLock();
  if (!gotTheLock) {
    app.quit();
  } else {
    app.on("second-instance", () => {
      // 当运行第二个实例时,将会聚焦到myWindow这个窗口
      if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore();
        mainWindow.focus();
      }
    });
  }
  // 设置开机自启动
  const isAutoOpen = store.get("autoOpen");
  if (isAutoOpen === false) {
    app.setLoginItemSettings({
      openAtLogin: false
    });
  } else {
    app.setLoginItemSettings({
      openAtLogin: true
    });
  }
  // 系统窗口控制函数
  ipcMain.on("win-close", () => {
    app.quit();
  });
  ipcMain.on("win-mini", () => {
    mainWindow.minimize();
  });
  ipcMain.on("win-resize", (e, mode) => {
    mainWindow.setResizable(true);
    if (mainWindow.isMaximized() && mode !== "max") {
      mainWindow.unmaximize();
    }
    if (mainWindow.isFullScreen() && mode !== "full") {
      mainWindow.setFullScreen(false);
    }
    if (mode === "normal") {
      mainWindow.setSize(1200, 720, true);
    } else if (mode === "middle") {
      mainWindow.setSize(1440, 960, true);
    } else if (mode === "max") {
      mainWindow.maximize();
    } else if (mode === "full") {
      mainWindow.setFullScreen(true);
    }
    if (mode !== "max" && mode !== "full") {
      mainWindow.center();
    }
    mainWindow.setResizable(false);
  });
  ipcMain.on("auto-open", (e, flag) => {
    store.set("autoOpen", flag);
    app.setLoginItemSettings({
      openAtLogin: flag
    });
  });
}
